/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.support.convert;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.persistence.AttributeConverter;
import javax.persistence.Convert;

/**
 * FieldConverterCache
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public class FieldConverterCache {
  private static final Map<Field, AttributeConverter<Object, Object>> CONVERTER_MAP =
      new ConcurrentHashMap<>();

  private FieldConverterCache() {}

  /**
   * 获取一个{@link AttributeConverter}实例
   *
   * @param field Java字段
   * @return {@link AttributeConverter}
   */
  @SuppressWarnings({"unchecked", "rawtype"})
  public static AttributeConverter<Object, Object> getConverterInstance(Field field) {
    AttributeConverter<Object, Object> converter = field == null ? null : CONVERTER_MAP.get(field);
    if (converter == null && field != null) {
      Convert convert = field.getAnnotation(Convert.class);

      if (convert != null) {
        Class<?> type = convert.converter();
        if (AttributeConverter.class.isAssignableFrom(type)) {
          converter = (AttributeConverter<Object, Object>) ReflectUtil.newInstance(type);
        } else {
          throw new RuntimeException(
              StrUtil.format("Not support convert type: {}", type.getName()));
        }
      }

      if (converter == null && field.getType().isEnum()) {
        converter = new EnumConverter(field);
      }

      if (converter != null) {
        CONVERTER_MAP.put(field, converter);
      }
    }

    return converter;
  }
}
